/*
 * @author dyh 2010-02-28
 * 管理员模拟ZSMS任意用户登录
 * */
package com.zjht.gmcc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zjht.gmcc.bean.SessionListener;
import com.zjht.gmcc.bean.model.UserSession;

import com.zjht.gmcc.bean.util.Menu;
import com.zjht.gmcc.bean.util.MyConstant;
import com.zjht.gmcc.bean.util.MyFormat;
import com.zjht.gmcc.bean.util.MyJDBC;
import com.zjht.gmcc.bean.util.MyParam;
import com.zjht.gmcc.bean.util.MyParamUtil;
import com.zjht.gmcc.bean.util.MySession;
 
public class Avatar extends HttpServlet {

	private static final long serialVersionUID = 5134302774945453643L;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		request.setCharacterEncoding("GBK");// 中文
		PrintWriter out = new PrintWriter(response.getOutputStream());
		if (!MySession.ValidSessionServlet(request, out, Menu.SYS_USERONLINE))
			return;
		if (!MyParamUtil.isMe(MySession.getUsercode(session))) {
			out.print("<script type='text/javascript'>alert('您无权访问此页面！');</script>");
			out.flush();
			out.close();
			return;
		}
		MyJDBC myJDBC = null;
		try {
			String strOK = request.getParameter("ok");
			String s_usercode = request.getParameter("usercode").trim().toUpperCase();
			String avator = MySession.getUsercode(session);

			myJDBC = new MyJDBC();
			// 检测用户名
			String s_sql = "SELECT operid,OperName,OrgaCode, DeptID,status FROM OPERS WHERE OperCode = ?";
			PreparedStatement ps = myJDBC.prepareStatement(s_sql);
			ps.setString(1, s_usercode);
			ResultSet rs = ps.executeQuery();
			if (!rs.next()) {
				out.print("<script>alert('用户(" + s_usercode + ")不存在。请您检查后再登录。');</script>");
				out.flush();
				out.close();
				return;
			}
			String status = rs.getString("status");
			if (!"1".equals(status)) {
				out.print("<script>alert('用户(" + s_usercode + ")已停用，无法模拟登录。请您启用后再模拟登录。');</script>");
				out.flush();
				out.close();
				return;
			}
			int userid = rs.getInt("operID");
			String username = "【模拟用户：" + rs.getString("OperName") + "】";
			String orgcode = rs.getString("OrgaCode");
			int deptid = rs.getInt("DeptID");

			// 检测组织是否停用
			s_sql = "SELECT orgid,ShortName OrgaName,OrgaTypeID,ActorCode,AreaID,channeltype FROM ORGANIZA WHERE OrgaCode = ? AND status='1'";
			ps = myJDBC.prepareStatement(s_sql);
			ps.setString(1, orgcode);
			rs = ps.executeQuery();
			if (!rs.next()) {
				out.print("<script>alert('对不起！您所在的组织已被停用，无法登录。请您与管理员联系。');</script>");
				out.flush();
				out.close();
				return;
			}
			int orgid = rs.getInt("Orgid");
			String orgname = rs.getString("OrgaName");
			int orgtype = rs.getInt("OrgaTypeID");
			String actorcode = rs.getString("ActorCode");
			int areaid = rs.getInt("AreaID");
			String channeltype = rs.getString("channeltype");
			if (strOK == null && SessionListener.IsLogoned(s_usercode)) {
				out.print("<form name='formok' method='post' action=''><input name='usercode' type='hidden' value='");
				out.print(s_usercode);
				out.print("' /></form><script>var isOK='1';if(confirm('此 ");
				out.print(s_usercode);
				out
						.print(" 帐号目前处于在线状态，可能是您未正常退出，或有人已在别处登录。\\n\\r\\n\\r您登录后是否需要和该用户同时在线？\\n\\r\\n\\r按“确定”：保持同时在线；按“取消”：将它踢下线。\\n\\r\\n\\r请您选择！')){isOK='0';}else{ ");
				out.print(" }document.all.formok.action='/Avatar?ok='+isOK;document.all.formok.submit();</script>");
				out.flush();
				out.close();
				return;
			}

			int dutyid = -1;
			s_sql = "SELECT dutyid FROM operspopedom WHERE OperCode = ?";
			ps = myJDBC.prepareStatement(s_sql);
			ps.setString(1, s_usercode);
			rs = ps.executeQuery();
			if (rs.next()) {
				dutyid = rs.getInt("DutyID");
			}

			String strIP = request.getRemoteAddr();
			// String strHost = request.getRemoteHost();

			// 取用户菜单
			String s_menuid = "";
			s_sql = "SELECT menuid FROM MENU WHERE menuid IN (SELECT b.menuid FROM OPERSPOPEDOM a, DUTYPOPEDOM b WHERE  a.opercode=? AND a.dutyid = b.dutyid ) AND (status = '1' OR status = '2') AND (channeltype='all' OR channeltype LIKE ?) AND (orgcode is null OR orgcode LIKE ?) ORDER BY dispid";
			ps = myJDBC.prepareStatement(s_sql);
			ps.setString(1, s_usercode);
			ps.setString(2, "%" + channeltype + "%");
			ps.setString(3, "%," + orgcode + ",%");
			boolean isEChannelCITY = true;// 是否为市移动独立操盘的电子渠道
			
			rs = ps.executeQuery();
			if (isEChannelCITY) {// 如果是市独立操盘或非电子渠道用户，则无需要处理菜单
				while (rs.next()) {
					s_menuid += rs.getString(1) + ",";
				}
			} else {// 如果是采用全省统一操盘的市移动用户，则需要屏蔽独立操盘电子渠道相关菜单
				int menuid = 0;
				boolean addMenu = true;// 是否需要添加菜单
				while (rs.next()) {
					menuid = rs.getInt(1);
					addMenu = true;
					if (menuid >= Menu.ECHANNEL && menuid < Menu.ECHANNEL + 100) {
						addMenu = false;
						for (int i = 0; i < Menu.ECHANNEL_GMCC_CITY_MENUS.length; i++) {
							if (menuid == Menu.ECHANNEL_GMCC_CITY_MENUS[i]) {
								addMenu = true;
								break;
							}
						}
					}
					if (addMenu)
						s_menuid += menuid + ",";
				}
			}
			// 如果用户没有任何菜单权限
			if (s_menuid.length() == 0) {
				session.invalidate();
				out.print("<script>alert('对不起，该用户无任何权限登录本系统！');</script>");
				out.flush();
				out.close();
				return;
			}
			session.setAttribute(MySession.USER_MENUID_ALL, s_menuid);// 用户所有菜单的id号,用逗号间隔，并以逗号结尾
			rs.close();
			rs = null;

			session.setAttribute("USER_DETAIL", "`" + areaid + "#" + username + "#" + orgname + "#" + strIP + "#" + MyFormat.getTodayFull());// 用户IP和登录时间等

			String deptname = MyParamUtil.getDeptName(deptid);

			String avatarcode = s_usercode + "[" + avator + "]";// 模拟用户的编码

			if (!"1".equals(strOK))// 如果不踢在线用户，则使用模拟编码作为用户编码
				s_usercode = avatarcode;

			SessionListener.RemoveUser(avatarcode);// 踢下该用户的模拟用户(即一个用户只能有一个模拟用户)
			SessionListener.UpdateSession(session, s_usercode);
			session.setAttribute(MySession.USER_AVATAR, s_usercode);// 模拟用户

			session.setAttribute(MySession.USER, new UserSession(userid, s_usercode, username, orgid, orgcode, orgname, orgtype, channeltype, deptid,
					deptname, dutyid, actorcode, areaid));

			try {
				s_sql = "INSERT INTO USERLOGON (opercode,ip,logondate) VALUES(?,?,SYSDATE)";
				ps = myJDBC.prepareStatement(s_sql);
				ps.setString(1, avatarcode);
				ps.setString(2, strIP);
				ps.executeUpdate();
			} catch (Exception exx) {
				// exx.printStackTrace();
				System.out.println("CheckUser.java(Insert into userlogon) error");
			} finally {
				MyJDBC.close(myJDBC);
			}

			
			session.setAttribute(MySession.TASK_FIRSTRELOAD, "1");
			// session.setAttribute(MyConstant.TASK_ZERODEPOTRESET,Task.intZeroDepotReset+"");

			out
					.print("<script>if(parent!=null&&parent.name=='mainFrame'){ parent.parent.leftFrame.document.body.onbeforeunload=function(){};parent.parent.leftFrame.document.body.onunload=function(){};}");
			out
					.print("	var win = window.open('/sysframe/avatarFirst.jsp','_manage','scroll=no,toolbar=no,menubar=no,titlebar=yes,directories=no,resizable=yes,status=yes,fullscreen=no,top=0,left=0,width=900,height=700');");
			out.print("	win.moveTo(0,0);");
			out.print("	win.resizeTo(screen.availWidth,screen.availHeight);");
			out.print("	if(window.parent.name!='_manage'){ ");
			out.print("		window.parent.opener=null;window.parent.close();");
			out.print("}</script>");
			out.flush();
			out.close();
		} catch (Exception e) {
			out.println("<script>alert('对不起，该用户在登录时遇到了问题。');</script>");
			out.flush();
			out.close();
			return;
		} finally {
			MyJDBC.close(myJDBC);
		}
	}
}
